package com.dynamicdatasource.config;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@PropertySource("classpath:db1.properties")
@PropertySource("classpath:db2.properties")
@MapperScan(basePackages= {"testdb.dynamicdatasource.mapper"},sqlSessionFactoryRef="sqlSessionFactoryBean")
public class DynamicDbConfig {
	@Bean("master")
	//@Primary
	@ConfigurationProperties(prefix = "spring.datasource.db2")
	public DataSource master() {
		return DataSourceBuilder.create().build();
	}

	@Bean("slave")
	@ConfigurationProperties(prefix = "spring.datasource.db1")
	public DataSource slave() {
	    return new DruidDataSource();
	}
	
	@Bean("dynamicDataSource")
	public DataSource dynamicDataSource(){
		Map<Object, Object> dataSourceMap = new HashMap<Object, Object>();
		dataSourceMap.put(DATASOURCE_MASTER, master());
		dataSourceMap.put(DATASOURCE_SLAVE, slave());
		
		DynamicDataSource dynamicDataSource = new DynamicDataSource();
		dynamicDataSource.setDefaultDataSource(master());
		dynamicDataSource.setDataSources(dataSourceMap);
		return dynamicDataSource;
	}
	
	@Bean("sqlSessionFactoryBean")
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        // 配置数据源，此处配置为关键配置，如果没有将 dynamicDataSource作为数据源则不能实现切换
        sessionFactory.setDataSource(dynamicDataSource());
        //sessionFactory.setTypeAliasesPackage("com.louis.**.model");    // 扫描Model
        //PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //sessionFactory.setMapperLocations(resolver.getResources("classpath*:**/sqlmap/*.xml"));    // 扫描映射文件
        return sessionFactory;
    }

    @Bean("transactionManager")
    public PlatformTransactionManager transactionManager() {
        // 配置事务管理, 使用事务时在方法头部添加@Transactional注解即可
        return new DataSourceTransactionManager(dynamicDataSource());
    }
    
    
    public static final String DATASOURCE_MASTER = "master";
    public static final String DATASOURCE_SLAVE = "slave";
}
